package com.feng.service.Impl;

import com.feng.dao.TagDao;
import com.feng.dto.Result;
import com.feng.pojo.Tag;
import com.feng.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    TagDao tagDao;

    @Override
    public Result getTag() {
        List<Tag> sortTag = new ArrayList<>();
        List<Tag> allTag = tagDao.findAll();
        for (Tag tag : allTag) {
            if (tag.getLevel() == 1) {
                sortTag.add(tag);
            } else {
                for (Tag tag1 : allTag) {

                    if (tag1.getId().intValue() == tag.getPTag()) {
                        List<Tag> nextTag = tag1.getNextTag();
                        if (nextTag == null) {
                            nextTag = new ArrayList<Tag>();
                        }
                        nextTag.add(tag);
                        tag1.setNextTag(nextTag);
                        break;
                    }
                }
            }
        }
        return Result.builder().success(true).massage("获取所有tag成功").data(sortTag).build();
    }

    public List<Tag> getByNameLike(String name) {
        List<Tag> btagByNameLike = tagDao.getByNameLike(name);
        return btagByNameLike;
    }

    @Override
    public Set<Integer> getLevel3Id(String name) {
        List<Tag> tempTag = tagDao.getByNameLike(name);
        Set<Tag> sortTag = new HashSet<>();
        Set<Integer> pTagIds = new HashSet<>();
        for (int i = 0; i < 3; i++) {
            sortTag.addAll(tempTag.stream()
                    .filter(tag -> tag.getLevel().equals(3))
                    .collect(Collectors.toSet()));
            pTagIds.addAll(tempTag.stream()
                    .filter(tag -> !tag.getLevel().equals(3))
                    .map(tag -> tag.getId())
                    .collect(Collectors.toSet()));
            tempTag = tagDao.getNextLevelTag(pTagIds);
        }
        return sortTag.stream().map(tag -> tag.getId()).collect(Collectors.toSet());
    }
}
